// 注册页面JavaScript
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('registerForm');
    const userTypeRadios = document.querySelectorAll('input[name="userType"]');
    const organizationFields = document.getElementById('organizationFields');
    const pilotFields = document.getElementById('pilotFields');
    
    let skillIndex = 0;
    let certificateIndex = 0;

    // 用户类型切换
    userTypeRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === '1') {
                // 飞手
                organizationFields.style.display = 'none';
                pilotFields.style.display = 'block';
                clearOrganizationFields();
            } else if (this.value === '2') {
                // 组织方
                pilotFields.style.display = 'none';
                organizationFields.style.display = 'block';
                clearPilotFields();
            }
        });
    });

    // 表单提交
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            submitForm();
        }
    });

    // 表单验证
    function validateForm() {
        const userType = document.querySelector('input[name="userType"]:checked');
        if (!userType) {
            showError('请选择用户类型');
            return false;
        }

        // 基本字段验证
        const requiredFields = ['userName', 'password', 'confirmPassword', 'realName', 'idCard', 'phone', 'emergencyContact', 'emergencyPhone'];
        for (let field of requiredFields) {
            const input = document.getElementById(field);
            if (!input.value.trim()) {
                showError(`${input.previousElementSibling.textContent}不能为空`);
                input.focus();
                return false;
            }
        }

        // 密码确认验证
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        if (password !== confirmPassword) {
            showError('两次输入的密码不一致');
            return false;
        }

        // 组织方特有字段验证
        if (userType.value === '2') {
            const orgRequiredFields = ['orgName', 'orgType', 'contactPerson'];
            for (let field of orgRequiredFields) {
                const input = document.getElementById(field);
                if (!input.value.trim()) {
                    showError(`${input.previousElementSibling.textContent}不能为空`);
                    input.focus();
                    return false;
                }
            }
        }

        // 飞手特有字段验证
        if (userType.value === '1') {
            const skills = document.querySelectorAll('.skill-item');
            if (skills.length === 0) {
                showError('请至少添加一个技能');
                return false;
            }

            for (let skill of skills) {
                const skillName = skill.querySelector('input[name*="skillName"]');
                const experienceYears = skill.querySelector('input[name*="experienceYears"]');
                if (!skillName.value.trim() || !experienceYears.value.trim()) {
                    showError('技能信息不完整');
                    return false;
                }
            }

            const certificates = document.querySelectorAll('.certificate-item');
            if (certificates.length === 0) {
                showError('请至少添加一个证书');
                return false;
            }

            for (let cert of certificates) {
                const certName = cert.querySelector('input[name*="certName"]');
                const certNumber = cert.querySelector('input[name*="certNumber"]');
                const certType = cert.querySelector('select[name*="certType"]');
                const issueDate = cert.querySelector('input[name*="issueDate"]');
                const expireDate = cert.querySelector('input[name*="expireDate"]');
                
                if (!certName.value.trim() || !certNumber.value.trim() || !certType.value || !issueDate.value || !expireDate.value) {
                    showError('证书信息不完整');
                    return false;
                }
            }
        }

        return true;
    }

    // 提交表单
    function submitForm() {
        const formData = new FormData(form);
        const data = {};
        
        // 收集表单数据
        for (let [key, value] of formData.entries()) {
            if (key.includes('[') && key.includes(']')) {
                // 处理数组字段
                const match = key.match(/^(\w+)\[(\d+)\]\.(\w+)$/);
                if (match) {
                    const [, arrayName, index, fieldName] = match;
                    if (!data[arrayName]) data[arrayName] = [];
                    if (!data[arrayName][index]) data[arrayName][index] = {};
                    data[arrayName][index][fieldName] = value;
                }
            } else {
                data[key] = value;
            }
        }

        // 添加验证码UUID（实际应该从后端获取）
        data.uuid = generateUUID();

        // 显示加载状态
        form.classList.add('loading');
        
        // 发送请求
        fetch('/drone/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            form.classList.remove('loading');
            if (result.code === 200) {
                showSuccess('注册成功，请等待审核');
                setTimeout(() => {
                    window.location.href = '/login';
                }, 2000);
            } else {
                showError(result.msg || '注册失败');
            }
        })
        .catch(error => {
            form.classList.remove('loading');
            showError('网络错误，请重试');
            console.error('Error:', error);
        });
    }

    // 添加技能
    window.addSkill = function() {
        skillIndex++;
        const container = document.getElementById('skillsContainer');
        const skillItem = document.createElement('div');
        skillItem.className = 'skill-item';
        skillItem.innerHTML = `
            <div class="form-group">
                <label>技能名称 *</label>
                <input type="text" name="skills[${skillIndex}].skillName" required>
            </div>
            <div class="form-group">
                <label>技能等级</label>
                <select name="skills[${skillIndex}].skillLevel">
                    <option value="">请选择</option>
                    <option value="初级">初级</option>
                    <option value="中级">中级</option>
                    <option value="高级">高级</option>
                </select>
            </div>
            <div class="form-group">
                <label>经验年限 *</label>
                <input type="number" name="skills[${skillIndex}].experienceYears" min="0" max="50" required>
            </div>
            <div class="form-group">
                <label>技能描述</label>
                <textarea name="skills[${skillIndex}].description" rows="2"></textarea>
            </div>
            <button type="button" class="btn-remove" onclick="removeSkill(this)">删除</button>
        `;
        container.appendChild(skillItem);
    };

    // 删除技能
    window.removeSkill = function(button) {
        button.parentElement.remove();
    };

    // 添加证书
    window.addCertificate = function() {
        certificateIndex++;
        const container = document.getElementById('certificatesContainer');
        const certItem = document.createElement('div');
        certItem.className = 'certificate-item';
        certItem.innerHTML = `
            <div class="form-group">
                <label>证书名称 *</label>
                <input type="text" name="certificates[${certificateIndex}].certName" required>
            </div>
            <div class="form-group">
                <label>证书编号 *</label>
                <input type="text" name="certificates[${certificateIndex}].certNumber" required>
            </div>
            <div class="form-group">
                <label>证书类型 *</label>
                <select name="certificates[${certificateIndex}].certType" required>
                    <option value="">请选择</option>
                    <option value="AOPA">AOPA</option>
                    <option value="UTC">UTC</option>
                    <option value="ASFC">ASFC</option>
                    <option value="OTHER">其他</option>
                </select>
            </div>
            <div class="form-group">
                <label>证书等级</label>
                <input type="text" name="certificates[${certificateIndex}].certLevel">
            </div>
            <div class="form-group">
                <label>发证日期 *</label>
                <input type="date" name="certificates[${certificateIndex}].issueDate" required>
            </div>
            <div class="form-group">
                <label>过期日期 *</label>
                <input type="date" name="certificates[${certificateIndex}].expireDate" required>
            </div>
            <div class="form-group">
                <label>证书图片 *</label>
                <input type="file" name="certificates[${certificateIndex}].certImage" accept="image/*" required>
            </div>
            <button type="button" class="btn-remove" onclick="removeCertificate(this)">删除</button>
        `;
        container.appendChild(certItem);
    };

    // 删除证书
    window.removeCertificate = function(button) {
        button.parentElement.remove();
    };

    // 刷新验证码
    window.refreshCaptcha = function() {
        const img = document.getElementById('captchaImg');
        img.src = '/captchaImage?t=' + new Date().getTime();
    };

    // 重置表单
    window.resetForm = function() {
        form.reset();
        clearOrganizationFields();
        clearPilotFields();
        organizationFields.style.display = 'none';
        pilotFields.style.display = 'none';
    };

    // 清空组织方字段
    function clearOrganizationFields() {
        const fields = ['orgName', 'orgType', 'legalPerson', 'businessLicense', 'contactPerson', 'contactEmail', 'description'];
        fields.forEach(field => {
            const input = document.getElementById(field);
            if (input) input.value = '';
        });
    }

    // 清空飞手字段
    function clearPilotFields() {
        const skillsContainer = document.getElementById('skillsContainer');
        const certificatesContainer = document.getElementById('certificatesContainer');
        
        // 保留第一个技能和证书项，清空其他
        const skills = skillsContainer.querySelectorAll('.skill-item');
        for (let i = 1; i < skills.length; i++) {
            skills[i].remove();
        }
        
        const certificates = certificatesContainer.querySelectorAll('.certificate-item');
        for (let i = 1; i < certificates.length; i++) {
            certificates[i].remove();
        }
        
        // 清空第一个项的内容
        skillsContainer.querySelectorAll('input, select, textarea').forEach(input => {
            input.value = '';
        });
        
        certificatesContainer.querySelectorAll('input, select, textarea').forEach(input => {
            input.value = '';
        });
    }

    // 显示错误信息
    function showError(message) {
        // 移除之前的错误信息
        const existingError = document.querySelector('.error-message');
        if (existingError) {
            existingError.remove();
        }
        
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message error';
        errorDiv.textContent = message;
        errorDiv.style.cssText = 'position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #ff4757; color: white; padding: 10px 20px; border-radius: 4px; z-index: 1000;';
        
        document.body.appendChild(errorDiv);
        
        setTimeout(() => {
            errorDiv.remove();
        }, 3000);
    }

    // 显示成功信息
    function showSuccess(message) {
        const successDiv = document.createElement('div');
        successDiv.className = 'success-message success';
        successDiv.textContent = message;
        successDiv.style.cssText = 'position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #2ed573; color: white; padding: 10px 20px; border-radius: 4px; z-index: 1000;';
        
        document.body.appendChild(successDiv);
        
        setTimeout(() => {
            successDiv.remove();
        }, 3000);
    }

    // 生成UUID
    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
});
